package org.camunda.bpm.getstarted.loanapproval.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

//@Component
//@Aspect
public class ApiServiceAspect {

private final Logger logger = LoggerFactory.getLogger(this.getClass());

/**
 * 切面
 */
    private final String POINT_CUT = "execution(* org.camunda.bpm.getstarted.loanapproval.controller..*.*(..))";

    @Pointcut(POINT_CUT)
    private void pointcut(){}

    @Before(value = POINT_CUT)
    public void before(JoinPoint joinPoint) {
    String className = joinPoint.getTarget().getClass().getName();
    String methodName = joinPoint.getSignature().getName();
    StringBuilder log = new StringBuilder();
    log.append("before: ")
    .append(className)
    .append("@")
    .append(methodName)
    .append(" , params: ");
    Object[] args = joinPoint.getArgs();
    for (Object arg : args) {
    log.append(JSON.toJSONString(arg) + ", ");
    }
    logger.info(log.toString());
    }

    @AfterReturning(value = "pointcut()", returning = "returnObj")
    public void afterReturn(Object returnObj) {
    String result = JSON.toJSONString(returnObj);
    logger.info("afterReturning: "+result);
    }

    @AfterThrowing(value = POINT_CUT, throwing = "e")
    public void afterThrowing(Throwable e) {
    logger.error("afterThrowing: "+e.getMessage(), e);
    }

    @Around(value = "pointcut()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    Long begin = System.currentTimeMillis();
    StringBuilder log = new StringBuilder("around: ");
    Object result = null;
    try {
    result = proceedingJoinPoint.proceed();
    } catch (Exception e) {
    logger.error(log + e.getMessage(), e);
    }
    Long end = System.currentTimeMillis();
    log.append(" 执行时间: ")
    .append(end-begin)
    .append("ms");
    return result;
}

}